package com.duan.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.duan.pojo.Role;
import com.duan.pojo.User;
import com.duan.service.role.RoleServiceImpl;
import com.duan.service.user.UserService;
import com.duan.service.user.UserServiceImpl;
import com.duan.util.Constants;
import com.duan.util.PageSupport;
import com.mysql.jdbc.StringUtils;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method != null && method.equals("savepwd")){ //前端有一个隐藏标签，设置键值对，如果读取出他的值是“savepwd”，代表需要修改密码，就执行此类下的修改密码方法updatePwd
            this.updatePwd(req, resp);
        }else if(method != null && method.equals("pwdmodify")){
            this.pwdModify(req, resp);
        }else if(method != null && method.equals("query")){
            this.query(req, resp);
        }else if(method != null && method.equals("add")){
            this.add(req, resp);
        }else if(method != null && method.equals("getrolelist")){
            this.getrolelist(req, resp);
        }else if(method != null && method.equals("ucexist")){
            this.userCodeExist(req, resp);
        }else if(method != null && method.equals("deluser")){
            this.deleteUser(req, resp);
        }else if(method != null && method.equals("modify")){
            this.getUserById(req, resp, "usermodify.jsp");
        }else if(method != null && method.equals("modifyexe")){
            this.modify(req, resp);
        }
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从Session里获取id！
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        boolean flag = false;

        //判断o是否存在 和 新的密码是否有效
        if(o != null && newpassword != null && newpassword.length() != 0){
            User user = (User)o;
            int id = user.getId();
            UserServiceImpl userService = new UserServiceImpl();
            System.out.println(newpassword);
            flag = userService.updatePwd(id, newpassword);

            //修改后的结果
            if(flag){
                //修改成功，就清空当前Session信息。
                req.setAttribute("message", "修改密码成功，请退出， 使用新的密码登录");
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else{
                //修改失败
                req.setAttribute("message", "修改密码失败");
            }
        }else{
            req.setAttribute("message", "新密码有问题！");
        }
        req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
    }

    //验证旧密码，session中有用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从session里面拿ID；
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        Map<String, String> Map = new HashMap<String, String>();

        if(o == null){ //session过期了， 需要写一个session默认过期时间web.xml中
            Map.put("result", "sessionerror");
        }else if(oldpassword == null && oldpassword.length() == 0){
            Map.put("result", "error");
        }else {
            String userPassword = ((User)o).getUserPassword(); //session中用户的密码
            if(oldpassword.equals(userPassword)){
                Map.put("result", "true");
            }else {
                Map.put("result", "false");
            }
        }

        //生成Json格式返回
        try{
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类，转换格式
            writer.write(JSONArray.toJSONString(Map));//传递给前端
            writer.flush();
            writer.close();
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    //重点、难点 用户表单信息
    public void query(HttpServletRequest req, HttpServletResponse resp){


        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;//刚进入页面时没有选择用户角色条件，默认为0

        //实例化ServiceImpl
        UserServiceImpl userService = new UserServiceImpl();

        //第一次走这个请求，一定是第一页，页面大小是固定的,所以先给默认值
        int pageSize = Constants.pageSize;//设置页面容量
        int currentPage = 1;//当前页码

        System.out.println("queryUserName servlet--------"+queryUserName);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);

        //根据前端输入，再修改默认值
        if(queryUserName == null){
            queryUserName = "";//一开始没有输入用户名，默认为""
        }
        if(temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp); //给查询赋值！ 0,1,2,3
        }
        if(pageIndex != null){
            currentPage = Integer.parseInt(pageIndex);
        }


        //获取用户总人数(分页： 上一页、下一页）
        int userCount = userService.getUserCount(queryUserName, queryUserRole);
        //实例化分页对象
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPage);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(userCount);

        //获取总页数
        int pageTotalPageCount = pageSupport.getTotalPageCount();

        //控制首页和尾页
        //如果页面小于1，就显示第一页的东西
        if(currentPage < 1){
            currentPage = 1;
        }else if(currentPage > pageTotalPageCount){//如果当前页面大于最后一页：
            currentPage = pageTotalPageCount;
        }

        //获取当页所有用户列表
        List<User> userList = userService.getUserList(queryUserName, queryUserRole, currentPage, pageSize);
        for (User user : userList) {
            System.out.println(user.getUserName());
        }
        req.setAttribute("userList", userList);
        //获去所有用户角色信息
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);

        req.setAttribute("totalCount", userCount);
        req.setAttribute("currentPageNo", currentPage);
        req.setAttribute("totalPageCount", pageTotalPageCount);


        //返回前端
        try{
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        }catch (ServletException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String userName = req.getParameter("userName");
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address =req.getParameter("address");
        String userRole = req.getParameter("userRole");

        User user = new User();
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.parseInt(gender));

        //获得SimpleDateFormat类，我们转换为yyyy-MM-dd的时间格式
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        try{
            //使用SimpleDateFormat的parse（）方法生成Date
            Date date = sf.parse(birthday);
            user.setBirthday(date);
        }catch (ParseException e){
            e.printStackTrace();
        }

        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        UserServiceImpl userService = new UserServiceImpl();
        if(userService.insertUser(user)){
            System.out.println("保存成功");
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        }else {
            System.out.println("保存失败");
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }

    }

    //获取角色列表
    public void getrolelist(HttpServletRequest req, HttpServletResponse resp) {

        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = null;
        roleList = roleService.getRoleList();

        resp.setContentType("application/json");
        try{
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(roleList));
            System.out.println(JSONArray.toJSONString(roleList));
            writer.flush();
            writer.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //判断用户账号是否可用
    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp){
        String userCode = req.getParameter("userCode");
        User user = null;

        Map<String, String> map = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            map.put("userCode", "exist");
        }else{
            UserServiceImpl userService = new UserServiceImpl();
            user = userService.selectUserCodeExist(userCode);
            if(user != null){
                map.put("userCode", "exist");
            }else {
                map.put("userCode", "noexist");
            }
        }
        try{
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
            writer.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //删除用户
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp){
        String userid = req.getParameter("uid");
        int id = 0;
        id = Integer.parseInt(userid);

        Map<String, String> map = new HashMap<String, String>();
        if(id <= 0){
            map.put("delResult", "notexist");
        }else{
            UserServiceImpl userService = new UserServiceImpl();
            if(userService.deleteUser(id)){
                map.put("delResult", "true");
                System.out.println("删除完成！");
            }else{
                map.put("delResult","false");
                System.out.println("删除失败！");
            }
        }

        try{
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    public void getUserById(HttpServletRequest req, HttpServletResponse resp, String url) throws ServletException, IOException {
        String id = req.getParameter("uid");

        if(!StringUtils.isNullOrEmpty(id)){
            //调用后台方法得到user对象
            UserService userService = new UserServiceImpl();
            User user = userService.selectUserById(Integer.parseInt(id));
            req.setAttribute("user", user);
            req.getRequestDispatcher(url).forward(req, resp);//获取到要修改的用户，跳转到usermodify.jsp界面。
        }
    }

    //修改用户信息
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        System.out.println("我读取到了信息");

        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setUserName(userName);
        user.setGender(Integer.parseInt(gender));
        try{
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        }catch (ParseException e){
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setModifyBy(((User)(req.getSession().getAttribute(Constants.USER_SESSION))).getId());
        user.setModifyDate(new Date());

        System.out.println("我准备将user信息发送到Service层");

        UserServiceImpl userService = new UserServiceImpl();
        if (userService.modifyUser(user)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do/method=query");
        }else{
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }
}
